const fs = require('fs')
const path = require('path')
const xlsx = require('node-xlsx');
const {
	mkdirsSync,
} = require('../utils')
const {
	getYearWeek,
	getTime,
	getDate,
} = require('../utils/dateUtils')

const _DBMySQL = require('../dbs/db-mysql')
const _mongoDB = require('../dbs/db-mongo')

const _WebDB = new _DBMySQL({
	host: "localhost",
	user: "root",
	port: 3306,
	password: "atmd@dd_2015",
	database: "web_crawler",
	charset: "utf8_general_ci"
})
const _webCrawlerMongo = new _mongoDB('mongodb://127.0.0.1:54188', 'web_crawler')

const titleId = ['source', 'list_id', 'list_name', 'tags', 'profile', 'itemid', 'itemname', 'artist', 'album', 'cp', 'exclusivity']
const titleName = ['来源', '歌单id', '标题', '标签', '简介', '歌曲ID', '歌曲名', '歌手名', '专辑名', '唱片公司', '付费方式']


async function buildExcel(options) {
	let {
		source,
		sourceName,
		minItem,
		week,
		filename
	} = options
	let matchSonglistCol = await _webCrawlerMongo.getCollection(`${source}_match_songlist`)
	let matchItemsCol = await _webCrawlerMongo.getCollection('match_items')
	let excelDir = path.resolve(`../data/excel/${week}`)
	mkdirsSync(excelDir)
	let list = await matchSonglistCol.find({
		week,
	}).toArray()
	let data = []
	data.push(titleName)
	let itemCount = 0
	let songlistCount = 0
	for (let i = 0; i < list.length; i++) {
		let songlist = list[i]
		if (songlist.item_ids.length < minItem)
			continue
		songlistCount += 1
		let {
			list_id,
			list_name,
			tags,
			profile,
			item_ids,
		} = songlist
		let itemList = await matchItemsCol.find({
			itemid: {
				$in: songlist.item_ids,
			},
		}).toArray()
		for (let i = 0; i < itemList.length; i++) {
			itemCount += 1
			let item = itemList[i]
			let d = []
			for (let j = 0; j < titleId.length; j++) {
				if (titleId[j] == 'source')
					d.push(sourceName)
				else
					d.push(songlist[titleId[j]] || item[titleId[j]])
			}
			data.push(d)
		}
	}
	let excelBuff = xlsx.build([{
		name: `${sourceName}歌单`,
		data
	}])
	fs.writeFileSync(path.join(excelDir, filename), excelBuff)
	return {
		itemCount,
		songlistCount,
	}
}

async function run() {
	let source = process.argv[2] || 'all'
	let minItem = process.argv[3] || 5
	let week = process.argv[4] || ''
	if (!week)
		return '缺少时间！'
	let sourceName = '全部'
	if (source == 'wy')
		sourceName = '网易'
	if (source == 'qq')
		sourceName = 'QQ'
	let expTaskCol = await _webCrawlerMongo.getCollection('exp_task')
	let task = await expTaskCol.findOne({
		week,
	})
	let exp_task_id = `${week}_${source}_min_${minItem}`
	let filename = `${sourceName}歌单_${week}_min_${minItem}.xlsx`
	filename = encodeURIComponent(filename)
	if (!task.exp_list[exp_task_id]) {
		task.exp_list[exp_task_id] = {
			exp_task_id,
			week,
			filename,
			minItem,
			sourceName,
			source,
			status: 0,
		}
		task.list = []
		for (let key in task.exp_list) {
			task.list.push(task.exp_list[key])
		}
		expTaskCol.updateOne({
			_id: task._id,
		}, {
			$set: {
				list: task.list,
				exp_list: task.exp_list,
				modify_time: getTime(),
			}
		})
	}
	// 创建Excel
	let {
		itemCount,
		songlistCount,
	} = await buildExcel({
		source,
		sourceName,
		minItem,
		week,
		filename
	})
	task = await expTaskCol.findOne({
		task_id: week,
	})
	task.exp_list[exp_task_id].status = 1
	task.exp_list[exp_task_id].itemCount = itemCount
	task.exp_list[exp_task_id].songlistCount = songlistCount
	task.list = []
	for (let key in task.exp_list) {
		task.list.push(task.exp_list[key])
	}
	return expTaskCol.findOneAndUpdate({
		_id: task._id,
	}, {
		$set: {
			exp_list: task.exp_list,
			list: task.list,
			modify_time: getTime(),
		}
	})
}

run().then(r => {
	console.log('---exportSonglistExcel.js--r---', r)
	setTimeout(() => {
		process.exit(0)
	}, 60000)
}).catch(e => {
	console.log('---exportSonglistExcel.js--e---', e)
	setTimeout(() => {
		process.exit(1)
	}, 60000)
})